<template>
    <div>
        <el-form label-width="80px" :model="form">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="角色名称">
                        <el-input placeholder="请输入角色名称" v-model="form.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="权限字符">
                        <el-input placeholder="请输入权限字符" v-model="form.authorityString"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态">
                        <el-select v-model="form.status" placeholder="请选择状态">
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="禁用" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="创建时间">
                        <el-date-picker
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            style="width: 250px;"
                            v-model="form.dateTime"
                            >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row>
            <el-col>
                <el-button type="primary" icon="el-icon-search" @click="initTable">查询</el-button>
                <el-button incon icon="el-icon-refresh-right" @click="clearForm">重置</el-button>
            </el-col>
        </el-row>
        <el-row>
            <el-col>
                <el-button type="primary" plain icon="el-icon-plus" @click="initObjFuncMenu()">新增</el-button>
                <el-button type="danger" plain icon="el-icon-delete" @click="deleteByIds">删除</el-button>
            </el-col>
        </el-row>

        <el-table
        :data="objDatas"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        >
        <el-table-column
        type="selection"
        width="55"
        >
        </el-table-column>
        <el-table-column
            prop="roleId"
            label="角色编号">
        </el-table-column>
        <el-table-column
            prop="roleName"
            label="角色名称">
        </el-table-column>
        <el-table-column
            prop="authorityString"
            label="权限字段">
        </el-table-column>
        <el-table-column
            label="职能菜单">
            <template v-slot="scope">
                <el-tag v-for="(bit, index) in scope.row.funcMenu" :key="index" type="success" v-show="bit == 1">
                {{ menuTitle[index] }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column
            label="状态">
            <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="handleSwitchChange(scope.row)">
            </el-switch>
            </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间">
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="更新时间">
        </el-table-column>
        <el-table-column
            label="操作">
            <template slot-scope="scope">
                <el-button type="text" icon="el-icon-edit"  @click="handleEdit(scope.$index, scope.row)" v-if="scope.row.roleId != 1">修改</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
         <!-- 分页 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>

        <el-dialog
        title="修改角色"
        :visible.sync="centerDialogVisible"
        width="30%"
        >
        <el-form label-width="100px" class="demo-ruleForm" :model="editForm" :rules="rule">
        <el-form-item label="角色名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="authorityString">
            <el-input v-model="editForm.authorityString"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
            <el-radio-group v-model="editForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item>
            <el-transfer v-model="value" :data="data" :titles="['未开通权限', '已拥有权限']"></el-transfer>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="eidtRole">确 定</el-button>
        </span>
        </el-dialog>

        <el-dialog
        title="新建角色"
        :visible.sync="createRoleVisible"
        width="30%">
            <el-form label-width="100px" class="demo-ruleForm" :model="newRoleObj" :rules="rule">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="newRoleObj.roleName"></el-input>
            </el-form-item>
            <el-form-item label="权限字符" prop="authorityString">
                <el-input v-model="newRoleObj.authorityString"></el-input>
            </el-form-item>
            <el-form-item label="角色状态" prop="status">
                <el-radio-group v-model="newRoleObj.status">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-transfer v-model="newRoleObj.haveMenu" :data="newRoleObj.funcMenu" :titles="['未开通权限', '已拥有权限']"></el-transfer>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="createRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
export default {
    name:'role',
    data(){
        return{
            value:[],
            data:[],
            form:{
                name:'',
                authorityString:'',
                status:'',
                dateTime:[],
            },
            objDatas:[],
            currentPage: 1,
            pageSize:10,
            total:0,
            funcMenu:'',
            menuTitle:['首页','员工管理','角色管理','全部通知','发布通知','业主档案','投诉工单','挪车请求',
            '全部房产','房产绑定','全部宠物','创建档案','全部装修','全部工单','全部车辆','车辆建档','全部访客'],
            selectionRowIds:[],
            centerDialogVisible: false,
            editForm:{
                id:Number,
                name:'',
                authorityString:'',
                status:'',
                funcMenu:[]
            },
            rule:{
                name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                authorityString: [
                    { required: true, message: '权限字符不能为空', trigger: 'blur' },
                    { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                ],
                roleName: [
                    { required: true, message: '名称不能为空', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
            },
            createRoleVisible: false,
            newRoleObj:{
                roleName: '',
                authorityString:'',
                status: '',
                funcMenu: [],
                haveMenu: []
            }
        }
    },
    created(){
        this.initAuthority()
        // this.c()
    },
    methods:{
        initAuthority(){
        this.$request.get("/role/authority",{
          params:{
            id: JSON.parse(localStorage.getItem("admin")).id,
            index: 2
          }
        })
        .then(res =>{
          this.Authority = res.data
          if(res.data == '1'){
            this.initTable()
          }else{
            this.$message.error("你没有权限访问此功能")
          }
        })
        .catch(err =>{
          console.log(err)
        })

      },
        initTable(){
            let startTime
            let endTime
            if(this.form.dateTime == null){
                startTime = ''
                endTime = ''
            }else{
                startTime = this.form.dateTime[0]
                endTime = this.form.dateTime[1]
            }

            this.$request.get("/role/page",{
                params:{
                    page: this.currentPage,
                    size: this.pageSize,
                    name: this.form.name,
                    authorityString: this.form.authorityString,
                    status: this.form.status,
                    startTime: startTime,
                    endTime: endTime
                }
            }).then(res => {
                this.objDatas = res.data.records
                this.total = res.data.total
                this.tempStatus = this.objDatas == 1? true : false
            }).catch(err => {
                console.error('Err:',err)
            })
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val
            this.getUserList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val
            this.getUserList();
        },
        clearForm(){
            this.form.name = ''
            this.form.authorityString = ''
            this.form.status = ''
            this.form.dateTime = []
            this.initTable()
        },
        handleSelectionChange(selection){
            // console.log("选中的数据为：",selection)
          this.selectionRowIds = []
          for(let i = 0;i < selection.length;i++){
            this.selectionRowIds.push(selection[i])
          }
          console.log("数组中的数据为",this.selectionRowIds)
        },
        deleteByIds(){
            console.log(this.selectionRowIds.length)
          if(this.selectionRowIds.length == 0){
            this.$message({
              showClose: true,
              message: '请先选择数据',
              type: 'warning'
            })
          }else{
            for(let i = 0;i<this.selectionRowIds.length;i++){
              if(this.selectionRowIds[i].status == true){
                this.$message({
                  showClose: true,
                  message: '启用用户不能被删除',
                  type: 'warning'
                })
                return
              }
            }
            this.$confirm('此操作将永久数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let ids = [];
              this.selectionRowIds.forEach(e =>{
                    ids.push(e.roleId)
                  })
              this.$request.delete("/role/delete",{
                      data: ids
              })
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: res.data+"条数据成功删除",
                  type: 'success'
                })
                this.initTable();
              })
              .catch(err => {
                      console.log(err)
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            })
            
           
          }
        },
        handleDelete(index,row){
          this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(row.status == true){
              this.$message({
                showClose: true,
                message: '管理员未被禁用，删除失败',
                type: 'warning'
              })
            }else{
              this.selectionRowIds.push(row.roleId)
              this.$request.delete("/role/delete",{
                data: this.selectionRowIds
              })
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: "数据已删除",
                  type: 'success'
                })
                this.initTable()
              })
              .catch(err => {
                console.log(err)
              })
            }
            this.selectionRowIds = []
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });

          
        },
        handleEdit(index, row){
            console.log(row.roleId)
            this.centerDialogVisible = true
            
            this.editForm.id = row.roleId
            this.editForm.name = row.roleName
            this.editForm.authorityString = row.authorityString
            this.editForm.status = row.status


            const values = []
            Array.from(row.funcMenu).forEach((c,index)=>{
                if(c == 1){
                    values.push(index)
                }
            })
            this.value = values           
            const datas = []
            console.log(this.menuTitle)
            this.menuTitle.forEach((menu,index)=>{
                datas.push({
                    label: menu,
                    key:index
                })
            })
            this.data = datas
        },
        eidtRole(){
             this.value.forEach((v)=>{
                this.editForm.funcMenu.push(this.menuTitle[v])
            })
            let str = ''
            this.menuTitle.forEach(m=>{
                if(this.editForm.funcMenu.includes(m)){
                    str += "1"
                }else{
                    str += "0"
                }
            })
            console.log(str)

            this.$request.put("/role/edit",{
                roleId: this.editForm.id,
                roleName: this.editForm.name,
                authorityString: this.editForm.authorityString,
                status: this.editForm.status,
                funcMenu:str
            })
            .then(res => {
                this.$notify({
                  title: '成功',
                  message: "更新成功",
                  type: 'success'
                })
                this.initTable()
            })
            .catch(err => {
                console.log(err)
            })
            this.editForm.funcMenu = []
            this.centerDialogVisible = false
            
        },
        handleSwitchChange(row) {
          // 在这里处理状态切换事件，你可以访问到状态切换的行数据 (row)
          console.log("Switch 状态改变了，行数据为：", row);
          // 这里可以放置你的其他逻辑
          console.log(row.id)
          this.$request.put("/role/edit",row)
          .then(res=>{
            // let id = res.data.id
            row = res.data
          })
          .catch(err=>{
            console.log(err)
          })
        },
        initObjFuncMenu(){
            this.createRoleVisible = true
            this.menuTitle.forEach((menu,index)=>{
                this.newRoleObj.funcMenu.push({
                    label: menu,
                    key:index
                })
            })
        },
        createRole(){
            let tempArr = []
            let str = ""
            this.newRoleObj.haveMenu.forEach((menu,index)=>{
                tempArr.push(this.menuTitle[menu])
            })

            this.menuTitle.forEach((m,index)=>{
                if(tempArr.includes(m)){
                    str += "1"
                }else{
                    str += "0"
                }
            })
            this.$request.put("/role/create",{
                    roleName:this.newRoleObj.roleName,
                    authorityString:this.newRoleObj.authorityString,
                    status:this.newRoleObj.status,
                    funcMenu:str
                
            }).then(res=>{
                console.log(res)
                this.$message({
                    type:'success',
                    message:res.data,
                    showClose: true,
                })
                this.initTable()
                this.createRoleVisible = false
            }).catch(err=>{
                console.log(err)
            })
            
        }
    }
}
</script>

<style>
  .el-row {
    margin-bottom: 20px;

  }
  .el-col {
    border-radius: 4px;
  }
  .el-form-item label{
    /* font-size: 15px; */
    font-weight: 900;
  }
  .el-tag{
    margin: 5px;
  }
</style>